package com.mobi.Survey.map;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.CancellationException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.mobi.Survey.lib.model.Address;
import com.mobi.Survey.lib.model.LatLong;

public class MapXmlParser extends DefaultHandler {

	private static final String GEOMETRY = "geometry";
	private static final String LAT = "lat";
	private static final String LNG = "lng";
	private StringBuffer value;
	private Address address;
	private double longitude;
	private double latitude;
	private boolean inGeometry;

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		value.append(new String(ch, start, length).trim().replaceAll("\t", "")
				.replaceAll("\n", ""));
	}

	private SAXParser saxParser;

	public MapXmlParser(Address address) {

		try {
			this.address = address;
			SAXParserFactory factory = SAXParserFactory.newInstance();
			saxParser = factory.newSAXParser();
		} catch (ParserConfigurationException e) {

			e.printStackTrace();
		} catch (SAXException e) {

			e.printStackTrace();
		}

	}

	public void parse(String xmlUrl) throws MalformedURLException, IOException,
			SAXException {
		InputStream isr = new URL(xmlUrl).openStream();
		saxParser.parse(isr, this);
	}

	@Override
	public void endDocument() throws SAXException {

	}

	@Override
	public void endElement(String uri, String localName, String qNames)
			throws SAXException {
		if (qNames.equalsIgnoreCase(GEOMETRY)) {
			address.setCoordinates(new LatLong(longitude, latitude));
			inGeometry = false;

			throw new CancellationException();
		} else if (qNames.equalsIgnoreCase(LAT) && inGeometry) {
			latitude = Double.parseDouble(value.toString());
		} else if (qNames.equalsIgnoreCase(LNG) && inGeometry) {
			longitude = Double.parseDouble(value.toString());
		}

	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		value = null;

		value = new StringBuffer();

		if (localName.equalsIgnoreCase(GEOMETRY)) {
			inGeometry = true;
		}

	}

}
